//
//  DateWheelViewController.m
//  KKZ
//
//  Created by  on 11-7-27.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "DateWheelViewController.h"
#import "UIViewController+BarItem.h"
#import "CustomTabBarViewController.h"


#define origin_x            160.0f
#define origin_y            460.0f
#define CLOCK_TWELVE_A          0.500000
#define CLOCK_TWELVE_B          -0.866025
#define CLOCK_ELEVEN_A          0.258819
#define CLOCK_ELEVEN_B          -0.965926
#define CLOCK_TEN_A             0.000000
#define CLOCK_TEN_B             -1.000000
#define CLOCK_NINE_A            -0.258819
#define CLOCK_NINE_B            -0.965926
#define CLOCK_EIGHT_A           -0.600000   
#define CLOCK_EIGHT_B           -0.866025
#define CLOCK_THIRTEEN_A        0.707107    
#define CLOCK_THIRTEEN_B        -0.707107
#define CLOCK_FOURTEEN_A        0.866025
#define CLOCK_FOURTEEN_B        -0.500000
#define CLOCK_FIFTEEN_A         0.965926
#define CLOCK_FIFTEEN_B         -0.258819
#define CLOCK_SIXTEEN_A         1.000000
#define CLOCK_SIXTEEN_B         0.000000
#define CLOCK_SEVENTEEN_A       0.965926
#define CLOCK_SEVENTEEN_B       0.258819
#define CLOCK_EIGHTEEN_A        0.866025
#define CLOCK_EIGHTEEN_B        0.500000
#define CLOCK_NINETEEN_A        0.707107
#define CLOCK_NINETEEN_B        0.707107
#define CLOCK_TWENTY_A          0.500000
#define CLOCK_TWENTY_B          0.866025
#define CLOCK_TWENTY_ONE_A      0.258819
#define CLOCK_TWENTY_ONE_B      0.965926
#define CLOCK_TWENTY_TWO_A      0.000000
#define CLOCK_TWENTY_TWO_B      1.000000
#define CLOCK_TWENTY_THREE_A    -0.258819
#define CLOCK_TWENTY_THREE_B    0.965926
#define CLOCK_TWENTY_FOUR_A     -0.520000
#define CLOCK_TWENTY_FOUR_B     0.866025

@implementation DateWheelViewController

@synthesize delegate;
@synthesize datePicker;
@synthesize timeLabel;

- (id)initWithDelegate:(id <DateDidFinishChooseDelegate>)aDelegate
{
    self = [super init];
    if (self) {
        self.delegate = aDelegate;
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)dateWillFinishChoose
{
    // Get the date picker date
    
    NSDate *aDate = [self.datePicker date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    date_ = [formatter stringFromDate:aDate];
    [formatter release];
    
    // combine the time and date
    NSString *dateString = [NSString stringWithFormat:@"%@ %@", date_, time_];
    NSLog(@"datestring: %@", dateString);
    [[NSUserDefaults standardUserDefaults] setValue:dateString forKey:@"my_date_time"];
     
    // send the change to delegate
    [delegate dateDidFinishChoose];
    CustomTabBarViewController *sharedController = [CustomTabBarViewController sharedTabBarController];
    
    [sharedController.tabBar setHidden:NO];
    
    // pop back
    [self dismissModalViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Set the view background
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
    
    // Add the wheel layer to view
    wheelLayer_ = [[CALayer layer] retain];
    wheelLayer_.backgroundColor = [UIColor clearColor].CGColor;
    wheelLayer_.bounds = CGRectMake(20, 136, 280, 280);
    wheelLayer_.position = CGPointMake(160, 416);
    wheelLayer_.delegate = self;
    wheelLayer_.contents = (id)[UIImage imageNamed:@"dataWheel.png"].CGImage;
    
    [self.view.layer insertSublayer:wheelLayer_ atIndex:0];
    
    wheelPickerLayer_ = [[CALayer layer] retain];
    wheelPickerLayer_.backgroundColor = [UIColor clearColor].CGColor;
    wheelPickerLayer_.bounds = CGRectMake(139, 136, 42, 140);
    wheelPickerLayer_.position = CGPointMake(160, 346);
    wheelPickerLayer_.delegate = self;
    wheelPickerLayer_.contents = (id)[UIImage imageNamed:@"dataWheel_picker.png"].CGImage;
    [self.view.layer addSublayer:wheelPickerLayer_];
    
    // Add the nav bar title
    [self addTitleToNavigationBar:@"选择时间"];
    
    // Add the back button
    [self createBarItemOn:kNavBarItemSideLeft frame:kNavBarLeftItemFrame title:@"确定" target:self action:@selector(dateWillFinishChoose)];
    
    // Configure the data picker
    time_ = @"15:30";
}

- (void)viewDidUnload
{
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)value:(CGFloat)aFloat isBelow:(CGFloat)high above:(CGFloat)low
{
    if (aFloat < high && aFloat >= low) {
        return YES;
    }
    return NO;
}

- (void)updateTimeInfo:(CATransform3D)transform
{
    if ([self value:transform.m11 isBelow:CLOCK_TWELVE_A above:CLOCK_ELEVEN_A] && 
        [self value:transform.m21 isBelow:CLOCK_TWELVE_B above:CLOCK_ELEVEN_B]) {
        time_ = @"11:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_ELEVEN_A above:CLOCK_TEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_ELEVEN_B above:CLOCK_TEN_B]) {
        time_ = @"10:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_TEN_A above:CLOCK_NINE_A] && 
             [self value:transform.m21 isBelow:CLOCK_NINE_B above:CLOCK_TEN_B]) {
        time_ = @"09:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_NINE_A above:CLOCK_EIGHT_A] && 
             [self value:transform.m21 isBelow:CLOCK_EIGHT_B above:CLOCK_NINE_B]) {
        time_ = @"08:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_THIRTEEN_A above:CLOCK_TWELVE_A] && 
             [self value:transform.m21 isBelow:CLOCK_THIRTEEN_B above:CLOCK_TWELVE_B]) {
        time_ = @"12:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_FOURTEEN_A above:CLOCK_THIRTEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_FOURTEEN_B above:CLOCK_THIRTEEN_B]) {
        time_ = @"13:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_FIFTEEN_A above:CLOCK_FOURTEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_FIFTEEN_B above:CLOCK_FOURTEEN_B]) {
        time_ = @"14:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_SIXTEEN_A above:CLOCK_FIFTEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_SIXTEEN_B above:CLOCK_FIFTEEN_B]) {
        time_ = @"15:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_SIXTEEN_A above:CLOCK_SEVENTEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_SEVENTEEN_B above:CLOCK_SIXTEEN_B]) {
        time_ = @"16:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_SEVENTEEN_A above:CLOCK_EIGHTEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_EIGHTEEN_B above:CLOCK_SEVENTEEN_B]) {
        time_ = @"17:30";;
    }
    else if ([self value:transform.m11 isBelow:CLOCK_EIGHTEEN_A above:CLOCK_NINETEEN_A] && 
             [self value:transform.m21 isBelow:CLOCK_NINETEEN_B above:CLOCK_EIGHTEEN_B]) {
        time_ = @"18:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_NINETEEN_A above:CLOCK_TWENTY_A] && 
             [self value:transform.m21 isBelow:CLOCK_TWENTY_B above:CLOCK_NINETEEN_B]) {
        time_ = @"19:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_TWENTY_A above:CLOCK_TWENTY_ONE_A] && 
             [self value:transform.m21 isBelow:CLOCK_TWENTY_ONE_B above:CLOCK_TWENTY_B]) {
        time_ = @"20:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_TWENTY_ONE_A above:CLOCK_TWENTY_TWO_A] && 
             [self value:transform.m21 isBelow:CLOCK_TWENTY_TWO_B above:CLOCK_TWENTY_ONE_B]) {
        time_ = @"21:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_TWENTY_TWO_A above:CLOCK_TWENTY_THREE_A] && 
             [self value:transform.m21 isBelow:CLOCK_TWENTY_TWO_B above:CLOCK_TWENTY_THREE_B]) {
        time_ = @"22:30";
    }
    else if ([self value:transform.m11 isBelow:CLOCK_TWENTY_THREE_A above:CLOCK_TWENTY_FOUR_A] && 
             [self value:transform.m21 isBelow:CLOCK_TWENTY_THREE_B above:CLOCK_TWENTY_FOUR_B]) {
        time_ = @"23:30";
    }
    
    self.timeLabel.text = time_;
}

- (CGFloat)pointDegree:(CGPoint)point
{
    if (point.x == 160) {
        return M_PI/2;
    }
    else if (point.y == 460) {
        if (point.x < 160) {
            return 0;
        }
        else {
            return M_PI;
        }
    }
    else {
        return atan((point.y - origin_y)/(point.x - origin_x));
    }
}

- (void)rotateBegin:(CGPoint)point toNewPoint:(CGPoint)newPoint
{
    CATransform3D currentTransform = wheelLayer_.transform;
    
    CGFloat point_abs_degree = [self pointDegree:point];
    CGFloat newpoint_abs_degree = [self pointDegree:newPoint];
    
    if (point_abs_degree > 0 && newpoint_abs_degree < 0) {
        point_abs_degree = -point_abs_degree;
    }
    else if (point_abs_degree < 0 && newpoint_abs_degree > 0) {
        newpoint_abs_degree = -newpoint_abs_degree;
    }
    
    CGFloat degree = point_abs_degree - newpoint_abs_degree;
    
    CATransform3D rotated = CATransform3DRotate(currentTransform, -degree, 0.0f, 0.0f, 1.0f);
    
    if (currentTransform.m11 < -0.5f && rotated.m11 < currentTransform.m11) {
        // Do nothing
    }
    else {
        wheelLayer_.transform = rotated;
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *aTouch = [touches anyObject];
    
    CGPoint point = [aTouch locationInView:self.view];
    
    _startPoint = point;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *aTouch = [touches anyObject];
    
    CGPoint currentPoint = [aTouch locationInView:self.view];
    
    [self rotateBegin:_startPoint toNewPoint:currentPoint];
    
    _startPoint = currentPoint;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    _startPoint = CGPointZero;
    
    [self updateTimeInfo:wheelLayer_.transform];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}


@end
